package com.security.filter;

import com.common.result.Result;
import com.common.util.CustomBeanUtil;
import com.security.domain.authority.CommonUserDetails;
import com.security.service.AuthenticateService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;

/**
 * @author zdh
 */
@Data
@Builder
@Slf4j
@RequiredArgsConstructor
public class TokenAuthFilter extends AbstractTokenAuthenticationFilter {
    private final AuthenticateService authenticateService;

    /**
     * 对当前用户状态进行检查,如果状态异常,返回false,否则返回true
     *
     * @param userDetails
     * @return
     */
    @Override
    protected boolean userStatusCheck(UserDetails userDetails) {
        //默认只会检查当前账户是否启用
        return userDetails.isEnabled();
    }

    /**
     * @param token 待验证令牌
     * @return 通过解析token来获取当前用户详细信息
     */
    @Override
    protected UserDetails verifyToken(String token) {
        Result result = authenticateService.verifyToken(token);
        if(result==null || result.getData()==null){
            return null;
        }
        return CustomBeanUtil.mapToBean((Map) result.getData(), new CommonUserDetails());
    }
}
